<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input 
          placeholder="请输入用户名" 
          v-model="queryParam.userName"
          clearable
          @clear="searchAdminUser"
          @change="searchAdminUser">
            <el-button slot="append" icon="el-icon-search" @click="searchAdminUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="tableData" border stripe>
        <el-table-column type="index" />
        <el-table-column label="用户名" prop="userName" />
        <el-table-column label="真实姓名" prop="realName" />
        <el-table-column label="性别" prop="sex" :formatter="sexFormatter" />
        <el-table-column label="创建时间" prop="ctime" />
        <el-table-column label="状态" prop="status" >
          <template v-slot="{row}">
            <el-tag :type="statusTagFormatter(row.status)">
              {{ statusFormatter(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px" >
          <template v-slot="{row}">
            <el-button size="mini" type="info" @click="changeStatus(row)">
              {{ statusBtnFormatter(row.status) }}
            </el-button>
            <el-button size="mini" type="primary" @click="showEditUserDialog(row.userId)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="removeUserById(row.userId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <pagination 
        v-show="total>0" 
        :total="total" 
        :page.sync="queryParam.pageIndex" 
        :limit.sync="queryParam.pageSize"
        @pagination="getAdminUserList"/>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
    title="添加用户"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form 
      :model="addForm" 
      :rules="addFormRules" 
      ref="addFormRef" 
      label-width="100px" >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio v-for="item in sexEnum" :key="item.key" :label="item.key" >{{ item.value }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status">
            <el-option v-for="item in statusEnum" :key="item.key" :value="item.key" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户的对话框 -->
    <el-dialog
    title="编辑用户"
    :visible.sync="editDialogVisible"
    width="50%">
      <!-- 内容主体区域 -->
      <el-form 
      :model="editForm" 
      :rules="editFormRules" 
      ref="editFormRef" 
      label-width="100px" >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" placeholder="不输入则不会改变密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio v-for="item in sexEnum" :key="item.key" :label="item.key" >{{ item.value }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option v-for="item in statusEnum" :key="item.key" :value="item.key" :label="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import userApi from '@/api/user'
import Pagination from '@/components/Pagination'
import { validateUserNameFn, validatePasswordFn } from '@/utils/validate'

export default {
  components: { Pagination },
  data() {
    const validateUserName = validateUserNameFn
    const validatePassword = validatePasswordFn
    return {
      // 查询用户的参数
      queryParam: {
        userName: '',
        role: undefined,
        pageIndex: undefined,
        pageSize: undefined,
      },
      // 获取到的用户总条数
      total: 0,
      // 表格数据的绑定对象
      tableData: [],
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        userName: '',
        realName: '',
        role: undefined,
        sex: undefined,
        status: undefined
      },
      // 添加表单的验证规则对象 
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 3, max: 8, message: '用户名的长度在3~8个字符之间', trigger: 'blur'},
          { validator: validateUserName, message: '用户名只能包含英文、数字', trigger: 'blur'}
        ],
        realName: [
          { required: true, message: '请输入用户名', trigger: 'blur'},
        ]
      },
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑用户的表单数据
      editForm: {
        userId: undefined,
        userName: '',
        realName: '',
        role: undefined,
        password: '',
        sex: undefined,
        status: undefined
      },
      // 编辑表单的验证规则对象 
      editFormRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 3, max: 8, message: '用户名的长度在3~8个字符之间', trigger: 'blur'},
          { validator: validateUserName, message: '用户名只能包含英文、数字', trigger: 'blur'}
        ],
        realName: [
          { required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          { validator: validatePassword, trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.queryParam.role = this.role.admin
    this.queryParam.pageIndex = this.page.index
    this.queryParam.pageSize = this.page.size
    this.addForm.role = this.role.admin
    this.addForm.sex = this.sexEnum[0].key
    this.addForm.status = this.statusEnum[0].key
    this.getAdminUserList()
  },
  methods: {
    // 条件搜索用户
    searchAdminUser() {
      this.queryParam.pageIndex = 1
      this.getAdminUserList()
    },
    // 获取管理员列表
    getAdminUserList() {
      userApi.getUserList(this.queryParam).then(data => {
        if (data.code === this.ok.code) {
          this.tableData = data.response.list
          this.total = data.response.total
          this.queryParam.pageIndex = data.response.pageNum
        }        
      })
    },
    // 改变用户状态
    changeStatus (row) {
      let _this = this
      userApi
        .changeStatus(row)
        .then(data => {
          if (data.code === this.ok.code) {
            row.status = data.response
            _this.$message.success(data.message)
          } else {
            _this.$message.error(data.message)
          }
        })
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      let _this = this
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return
        }
        // 发起添加用户的请求
        userApi
          .editUser(_this.addForm)
          .then(data => {
            // 添加用户成功
            if (data.code === _this.ok.code) {
              // 提示成功信息  TODO 会重复刷新消息通知
              // _this.$message.success(data.message)
              // 关闭对话框
              _this.addDialogVisible = false
              // 重新获取表格数据
              _this.searchAdminUser()
            } else {
              _this.$message.error(data.message)
              _this.$refs.addFormRef.resetFields()
            }
          })
      })
    },
    // 展开编辑用户对话框
    showEditUserDialog(userId) {
      let _this = this
      // 获取用户Id
      userApi
        .getUserById(userId)
        .then(data => {
          if (data.code === _this.ok.code) {
            _this.editForm = data.response
            _this.editDialogVisible = true
          } else {
            _this.$message.error(data.message)
          }
        })
    },
    // 点击按钮，修改用户信息
    editUser() {
      let _this = this
      this.$refs.editFormRef.validate(valid => {
        if (!valid) {
          return
        }
        _this.editForm.role = _this.role.admin
        // 发起编辑用户的请求
        userApi
          .editUser(_this.editForm)
          .then(data => {
            if (data.code === _this.ok.code) {
              // 提示成功信息
              _this.$message.success(data.message)
              // 关闭对话框
              _this.editDialogVisible = false
              // 重新获取表格数据
              _this.searchAdminUser()
            } else {
              _this.$message.error(data.message)
              _this.editDialogVisible = false
            }
          })
      })
    },
    // 根据id删除对应的用户信息
    async removeUserById (userId) {
      // 弹窗询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?', 
        '提示', 
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      userApi
        .removeUserById(userId)
        .then(data => {
          if (data.code === this.ok.code) {
            // 提示成功信息
            this.$message.success(data.message)
            // 重新获取表格数据
            this.searchAdminUser()
          } else {
            this.$message.error(data.message)
          }
        })
    },
    // 性别转换
    sexFormatter (row, column, cellValue, index) {
      return this.enumFormat(this.sexEnum, cellValue)
    },
    // 用户状态转换
    statusFormatter (status) {
      return this.enumFormat(this.statusEnum, status)
    },
    // 用户状态tag转换
    statusTagFormatter (status) {
      return this.enumFormat(this.statusTag, status)
    },
    // 用户状态按钮转换
    statusBtnFormatter (status) {
      return this.enumFormat(this.statusBtn, status)
    }
  },
  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapState('user', {
      role: state => state.role
    }),
    ...mapState('page', {
      page: state => state.page
    }),
    ...mapState('resCode', {
      ok: state => state.OK
    }),
    ...mapState('enumItem', {
      sexEnum: state => state.user.sexEnum,
      statusEnum: state => state.user.statusEnum,
      statusTag: state => state.user.statusTag,
      statusBtn: state => state.user.statusBtn
    })
  }
}
</script>
